package bilibili;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Solution {

    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);
        final int M = scanner.nextInt();
        final int N = scanner.nextInt();
        if (M == -1 && N == -1) {
            return;
        }
        long[][] arr = new long[M][N];
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                arr[i][j] = scanner.nextLong();
            }
        }
        final List<Long> integers = spiralOrder1(arr);
        for (int i = 0; i < integers.size(); i++) {
            if (i == integers.size() - 1) {
                System.out.print(integers.get(i));
            } else {
                System.out.print(integers.get(i) + ",");
            }
        }
    }

    public static List<Long> spiralOrder(long[][] matrix) {
        List<Long> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;
        int rows = matrix.length, columns = matrix[0].length;
        boolean[][] vis = new boolean[rows][columns];
        int total = rows * columns;
        int r = 0, c = 0;
        //  右 下 左 上
        int[][] dxy = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        // 方向标志
        int d = 0;
        for (int i = 0; i < total; i++) {
            res.add(matrix[r][c]);
            vis[r][c] = true;
            //计算下一位置
            int nextRow = r + dxy[d][0], nextColumn = c + dxy[d][1];
            // 判断是否越界或者访问过 进行转弯
            if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || vis[nextRow][nextColumn]) {
                d = (d + 1) % 4;
            }
            //改变行列位置
            r += dxy[d][0];
            c += dxy[d][1];
        }
        return res;
    }

    public static List<Long> spiralOrder1(long[][] matrix) {
        List<Long> list = new ArrayList<>();
        if (matrix == null || matrix.length == 0) {
            return list;
        }
        int m = matrix.length; //行
        int n = matrix[0].length; //列
        int i = 0;
        //层数
        int count = (Math.min(m, n) + 1) / 2;
        //从外部向内部遍历
        while (i < count) {
            for (int j = i; j < n - i; j++) {
                //从左到右
                list.add(matrix[i][j]);
            }
            for (int j = i + 1; j < m - i; j++) {
                //最右边的从上到下
                list.add(matrix[j][(n - 1) - i]);
            }
            //(m-1-i!=i) 如果只有一行, 不需要打印了， 第一次遍历已经打印了
            for (int j = (n - 1) - (i + 1); j >= i && (m - 1 - i != i); j--) {
                //最下面 从右到左
                list.add(matrix[(m - 1) - i][j]);
            }
            for (int j = (m - 1) - (i + 1); j >= i + 1 && (n - 1 - i != i); j--) {
                list.add(matrix[j][i]);
            }
            i++;
        }
        return list;
    }
}